package com.example.zn.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zn.dto.Result;
import com.example.zn.entity.Admin;
import com.example.zn.service.AdminService;
import com.example.zn.mapper.AdminMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author ZN
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2024-03-18 09:39:04
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{
    @Override
    public Result login(Admin admin) {
        //根据用户名查询用户是否存在
        //创建查询条件构造器 (select * from admin  where username=XXX)
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("uname",admin.getUname());
        //根据给定的条件构造器查询对象
        Admin a = getOne(query);
        if(Objects.isNull(a)){
            //链式编程
            return Result.fail().setMsg("用户不存在");
        }
        if(a.getStatus() != 0){
            return Result.fail().setMsg("账号禁用").setCode(1);
        }

        //将数据库中用户的盐取出并与用户输入的密码组合加密
        String pwd = SecureUtil.md5(admin.getPassword()+a.getSalt());
        admin.setPassword(pwd);

        if(Objects.equals(a.getPassword(),admin.getPassword())){
            return Result.ok().setMsg("登录成功").setData(a);
        }
        return Result.fail().setMsg("密码错误").setCode(2);
    }

    @Override
    public Result reg(Admin admin) {
        //执行注册前需要先检查用户名是否重复
        //创建查询条件构造器 (select * from admin  where username=XXX)
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("uname",admin.getUname());
        //根据给定的条件构造器查询对象
        Admin a = getOne(query);
        if(Objects.nonNull(a)){
            return Result.fail().setMsg("该账号已存在");
        }
        //生成随机盐
        String salt = RandomUtil.randomString(6);
        admin.setSalt(salt);
        //将随机盐和输入的密码组合加密
        String pwd = admin.getPassword() + salt;
        //使用MD5对组合后的密码加密
        pwd = SecureUtil.md5(pwd);
        //填充加密后的密码到对象中
        admin.setPassword(pwd);
        //执行添加 并判断
        if(save(admin)){
            return Result.ok().setMsg("添加成功").setData(admin);
        }
        return Result.fail().setMsg("添加失败").setCode(1);
    }
}




